package user

import (
	"cloudstation/util"
	"encoding/json"
	"os"
)

type User struct {
	Username       string `json:"username" validate:"required`
	Password       string `json:"password" validate:"required`
	BuckName       string `json:"buckName" validate:"required`
	BucketEndpoint string `json:"buckEndpoint" validate:"required`
	AccessID       string `json:"accessid" validate:"required`
	AccessKey      string `json:"accesskey" validate:"required`
	Provider       string `json:"provider" validate:"required"`
}

func NewUser(username, password, buckname, bucketEndpoint, accessid, accesskey, provider string) (*User, error) {
	user := &User{
		Username:       username,
		Password:       password,
		BuckName:       buckname,
		BucketEndpoint: bucketEndpoint,
		AccessID:       accessid,
		AccessKey:      accesskey,
		Provider:       provider,
	}
	if err := util.Validate(user); err != nil {
		return nil, err
	}
	return user, nil

}

const (
	jsonPath = `E:/Go/Project/Demo/day-2021-0728/cloudstation/data/user.json`
)

func ReadData() (map[string]*User, error) {
	isok, _ := PathExists(jsonPath)
	m := make(map[string]*User)
	if isok {
		b, err := os.ReadFile(jsonPath)
		if err != nil {
			return nil, err
		}
		err = json.Unmarshal(b, &m)
		if err != nil {
			return nil, err
		}

	}
	return m, nil

}

func WriteData(m map[string]*User) error {
	f, err := os.Create(jsonPath)
	if err != nil {
		return err
	}
	defer f.Close()
	b, err := json.Marshal(m)
	if err != nil {
		return err
	}
	_, err = f.Write(b)
	return err
}

func PathExists(path string) (bool, error) {

	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
